package com.lagou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lagou.entity.CourseComment;
import com.lagou.service.CourseCommentService;
import mapper.CourseCommentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 课程留言表(CourseComment)表服务实现类
 *
 * @author Gilbert
 * @since 2021-06-28 20:44:49
 */
@Service(interfaceClass = CourseCommentService.class)
public class CourseCommentServiceImpl implements CourseCommentService {
    @Autowired
    private CourseCommentDao courseCommentDao;

    /**
     * 保存留言
     *
     * @param courseComment 实例对象
     * @return 影响行数
     */
    @Override
    public Integer saveComment(CourseComment courseComment) {
        return courseCommentDao.saveComment(courseComment);
    }

    /**
     * 获取课程留言
     *
     * @param courseId 课程编号
     * @param offset   数据偏移
     * @param pageSize 每页条目数
     * @return 留言对象列表
     */
    @Override
    public List<CourseComment> getCommentsByCourseId(Integer courseId, Integer offset, Integer pageSize) {
        return courseCommentDao.getCommentsByCourseId(courseId, offset, pageSize);
    }

    /**
     * 点赞
     *
     * @param commentId 留言编号
     * @param userId    用户编号
     * @return 0:保存失败，1:保存成功
     */
    @Override
    @Transactional
    public Integer saveFavorite(Integer commentId, Integer userId) {
        boolean liked = courseCommentDao.existsFavorite(commentId, userId) == 1;
        boolean saved;
        if (liked) {
            saved = courseCommentDao.updateFavoriteStatus(0, commentId, userId) == 1;
        } else {
            saved = courseCommentDao.saveCommentFavorite(commentId, userId) == 1;
        }
        boolean counted = courseCommentDao.updateLikeCount(1, commentId) == 1;

        if (!saved || !counted) {
            // 手动回滚+返回值
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }

        return 1;
    }

    /**
     * 取消点赞
     *
     * @param commentId 留言编号
     * @param userId    用户编号
     * @return 0:保存失败，1:保存成功
     */
    @Override
    @Transactional
    public Integer cancelFavorite(Integer commentId, Integer userId) {
        boolean canceled = courseCommentDao.updateFavoriteStatus(1, commentId, userId) == 1;
        boolean counted = courseCommentDao.updateLikeCount(-1, commentId) == 1;

        if (!canceled || !counted) {
            // 手动回滚+返回值
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }

        return 1;
    }
}
